﻿/**
 *    Copyright 2012 Yohan Courbe
 *
 *  Licensed under the Apache License, Version 2.0 (the "License 
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *      
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

using System.Linq;
using System.Collections;
using System.Net;

namespace NetworkAnalyzer.Engines.UdpTransfertTracker
{
    class UdpTransfertList : IEnumerable
    {
        private readonly ArrayList _udpTransferts = new ArrayList();

        public IEnumerator GetEnumerator()
        {
            return _udpTransferts.GetEnumerator();
        }

        public void Add(UdpTransfert udpTransfert)
        {
            _udpTransferts.Add(udpTransfert);
        }

        public void Remove(UdpTransfert udpTransfert)
        {
            _udpTransferts.Remove(udpTransfert);
        }

        public int Count
        {
            get { return _udpTransferts.Count; }
        }

        public UdpTransfertList()
        {

        }

        public UdpTransfertList(UdpTransfertList copy)
        {
            _udpTransferts = new ArrayList(copy._udpTransferts);
        }

        public UdpTransfert GetUdpTransfert(IPAddress localhost, ushort localport, IPAddress remotehost, ushort remoteport)
        {
            foreach (var udpTransfert in _udpTransferts.Cast<UdpTransfert>().Where(udpTransfert => udpTransfert.Match(localhost, localport, remotehost, remoteport)))
            {
                return udpTransfert;
            }

            var newUdpTransfert = new UdpTransfert(localhost, localport, remotehost, remoteport);
            _udpTransferts.Add(newUdpTransfert);

            return newUdpTransfert;
        }
    }
}
